var mongoose = require('mongoose');
var Nightmare = require('nightmare');
var vo=require('vo');
mongoose.connect('mongodb://localhost/test');

var TestFirst = new mongoose.Schema({
  XH : {type : Number},
  URL : {type : String},
  GCYPMC:{type:String},
  PZWH:{type:String},
  SCDW:{type:String},
  ZJ:{type:String},
  GG:{type:String}
});

var YPB  =mongoose.model('YPB',TestFirst);

  var ypb=new YPB();
var nightmare = Nightmare({
	show: true,  //浏览器默认是没有head
	openDevTools: true,//自动打开开发工具
	waitTimeout: 90000000//请求超时就终止
});



//访问url
var url='http://app2.sfda.gov.cn/datasearchp/all.do?page=1&tableName=TABLE25&formRender=count&searchcx=&name=对乙酰氨基酚片';
/**
 * 读取总数
 * @return {[type]} [description]
 */
function get_page() {
	//找出含有page标签的元素
  let pages=[].slice.call(document.querySelectorAll('html body center table tbody tr td table tbody tr td table tbody tr[height="70"]'));//获取总页数
	let page= pages[0].innerText;
	//总条数
	let page_SMS=parseInt((page.split("条")[0]).split(" ")[1]);
	//总页数
  let page_count=parseInt(((page.split("/")[1]).split("页")[0]).split("共")[1]);

 return {page_SMS,page_count};
}




/**
 * 循环读取药品列表
 * @return {[type]} [description]
 */
function tr_name() {
  var td_Elements='html body center table tbody tr td table tbody tr td table.msgtab tbody tr';//解析的tr
  //解析列表
	let list_td = [];
  var tr_arr=[].slice.call(document.querySelectorAll(td_Elements));//读取到全部的tr数组
   for(var i=1;i<tr_arr.length;i++){//每一个tr下面有诸多个td
    var arr=tr_arr[i].querySelectorAll('td');
		//获取药品名称
			list_td.push({
				XH:arr[0].textContent,
				URL:arr[1].querySelector('a').href,
				GCYPMC:arr[1].textContent,
				PZWH:arr[2].textContent,
				SCDW:arr[3].textContent,
				ZJ:arr[4].textContent,
				GG:arr[5].textContent
			});
	}
	  return list_td;
};

/**
 * 执行
 * @type {[type]}
 */
vo(function *() {
		nightmare.goto(url)
							.wait('tbody');
	 let result=yield nightmare.evaluate(get_page);
	 console.log(result.page_SMS);
		 for (var i = 1; i < 6; i++) {
		 	let new_url=`http://app2.sfda.gov.cn/datasearchp/all.do?page=${i}&tableName=TABLE25&formRender=count&searchcx=&name=对乙酰氨基酚片`;
			yield nightmare.goto(new_url);
			yield nightmare.wait('tbody');
		  // let td_test=yield nightmare.evaluate(tr_name);
      let td_test=yield nightmare.evaluate(tr_name);
      console.log(td_test);
			// console.log(td_test);
		}
  yield ypb.insert(td_test);
		// return td_test;
})((err, result) => {
  if(err)
    console.log(err);
  else
    console.log(result);
});
